import * as React from "react"
import { type SearchParams } from "@/types/table"
import { getValidFilters } from "@/lib/data-table"
import { Skeleton } from "@/components/ui/skeleton"
import { DataTableSkeleton } from "@/components/data-table/data-table-skeleton"
import { Shell } from "@/components/shell"
import { getServerSession } from "next-auth"
import { authOptions } from "@/app/api/auth/[...nextauth]/route"
import Link from "next/link"
import { Button } from "@/components/ui/button"
import { LogIn } from "lucide-react"
import { getSHIEvaluationSubmissions } from "@/lib/evaluation-submit/service"
import { getSHIEvaluationsSubmitSchema } from "@/lib/evaluation-submit/validation"
import { SHIEvaluationSubmissionsTable } from "@/lib/evaluation-submit/table/submit-table"
import { useTranslation } from "@/i18n"

interface IndexPageProps {
  params: Promise<{lng: string}>
  searchParams: Promise<SearchParams>
}

export default async function IndexPage(props: IndexPageProps) {
  const searchParams = await props.searchParams
  const search = getSHIEvaluationsSubmitSchema.parse(searchParams)
  const validFilters = getValidFilters(search.filters)
  const {lng} = await props.params
  const {t} = await useTranslation(lng, 'menu')

  // Get session
  const session = await getServerSession(authOptions)
  
  // Check if user is logged in
  if (!session || !session.user) {
    // Return login required UI instead of redirecting
    return (
      <Shell className="gap-6">
        <div className="flex items-center justify-between">
          <div>
            <div className="flex items-center gap-2">
              <h2 className="text-2xl font-bold tracking-tight">
                {t('menu.vendor_management.evaluation_input')}
              </h2>
            </div>
            {/* <p className="text-muted-foreground">
            요청된 정기평가를 입력하고 제출할 수 있습니다. 
            </p> */}
          </div>
        </div>

        <div className="flex flex-col items-center justify-center py-12 text-center">
          <div className="rounded-lg border border-dashed p-10 shadow-sm">
            <h3 className="mb-2 text-xl font-semibold">로그인이 필요합니다</h3>
            <p className="mb-6 text-muted-foreground">
            정기평가를 확인하려면 먼저 로그인하세요.
            </p>
            <Button size="lg" asChild>
              <Link href="/partners">
                <LogIn className="mr-2 h-4 w-4" />
                로그인하기
              </Link>
            </Button>
          </div>
        </div>
      </Shell>
    )
  }
  
  const userId = session.user.id
  
  // Validate vendorId (should be a number)
  const idAsNumber = Number(userId)

  
  if (isNaN(idAsNumber)) {
    // Handle invalid vendor ID (this shouldn't happen if authentication is working properly)
    return (
      <Shell className="gap-6">
        <div className="flex items-center justify-between">
          <div>
            <h2 className="text-2xl font-bold tracking-tight">
            {t('menu.vendor_management.evaluation_input')}
            </h2>
          </div>
        </div>
        <div className="flex flex-col items-center justify-center py-12 text-center">
          <div className="rounded-lg border border-dashed p-10 shadow-sm">
            <h3 className="mb-2 text-xl font-semibold">계정 오류</h3>
            <p className="mb-6 text-muted-foreground">
               관리자에게 문의하세요.
            </p>
          </div>
        </div>
      </Shell>
    )
  }
  
  // If we got here, we have a valid vendor ID
  const promises = Promise.all([
    getSHIEvaluationSubmissions({
      ...search,
      filters: validFilters,
    }, idAsNumber)
  ])
  
  return (
    <Shell className="gap-2">
      <div className="flex items-center justify-between space-y-2">
        <div className="flex items-center justify-between space-y-2">
          <div>
            <h2 className="text-2xl font-bold tracking-tight">
            {t('menu.vendor_management.evaluation_input')}
            </h2>
            {/* <p className="text-muted-foreground">
            요청된 정기평가를 입력하고 제출할 수 있습니다. 
            </p> */}
          </div>
        </div>
      </div>
      
      <React.Suspense fallback={<Skeleton className="h-7 w-52" />}>
        {/* DateRangePicker can go here */}
      </React.Suspense>
      
      <React.Suspense
        fallback={
          <DataTableSkeleton
            columnCount={6}
            searchableColumnCount={1}
            filterableColumnCount={2}
            cellWidths={["10rem", "40rem", "12rem", "12rem", "8rem", "8rem"]}
            shrinkZero
          />
        }
      >
        <SHIEvaluationSubmissionsTable promises={promises} />
      </React.Suspense>
    </Shell>
  )
}